package tictactoe;

public class Strategy {

	private Board board = null;
	private char mySymbol;
	private char theirSymbol;
	
	public Strategy(char symbol){
		this(symbol, (symbol == Board.CROSS ? Board.NAUGHT : Board.CROSS));
	}
	
	public Strategy(char symbol, char opsymbol){
		theirSymbol = opsymbol;
		mySymbol = symbol;
	}
	
	public void move(Board b){
		//try to take central cell
		try{
			b.tryInsert(mySymbol, 1, 1);
			return;
		}catch(SquareOccupiedException e){
			System.err.println("Central cell occupied!");
		}catch(InvalidSymbolException e){
			System.err.println("BAD SYMBOL!");
		}
		
		//now try finding a square such that win can be made in 1 move
		for(int i=0; i < 3; i++)
			for(int k=0; k < 3; k++){
				int wins = 0;
				try{
					wins = b.tryInsert(mySymbol, i, k);
					b.clear();
					return;
				}catch(SquareOccupiedException e){
					System.err.println("Cell " + i + ", " + k + " is occupied");
				}catch(InvalidSymbolException e){
					System.err.println("BAD SYMBOL!");
				}
				if (wins > 0) return;
			}
		
		//now try finding were opponent can win in 1 move
		for(int i=0; i < 3; i++)
			for(int k=0; k < 3; k++){
				int wins = 0;
				try{
					wins = b.tryInsert(theirSymbol, i, k);
					if (wins > 0) b.place(mySymbol, i, k); //go there :)
					b.clear();
					return;
				}catch(SquareOccupiedException e){
					System.err.println("Cell " + i + ", " + k + " is occupied");
				}catch(InvalidSymbolException e){
					System.err.println("BAD SYMBOL!");
				}
				if (wins > 0) return;
			}
	}
}
